package org.abacus.hibernate;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.hibernate.Session;
import org.hibernate.stat.Statistics;

/**
 *
 * @author chaoyang.li
 * @since 2012-08-30
 */
public abstract class HibernateSessionProvider {

	private static final HibernateSessionFactoryProvider hibernateSessionFactoryProvider = HibernateSessionFactoryProvider.getInstance();

	private static final Map<String, ThreadLocal<Session>> sessions = new ConcurrentHashMap<String, ThreadLocal<Session>>();

	public static final synchronized void addTag(String tag) {
		hibernateSessionFactoryProvider.addTag(tag);
		if (null == sessions.get(tag)) {
			sessions.put(tag, new ThreadLocal<Session>());
		}
	}

	/**
	 * @author chaoyang.li
	 * */
	public static final Set<String> getTags() {
		return hibernateSessionFactoryProvider.getTags();
	}

	/**
	 * @author chaoyang.li
	 * @param tag
	 */
	public static final synchronized Session getCurrentSession(String tag) {
		if (sessions.get(tag).get() == null) {
			return openSession(tag);
		}
		return sessions.get(tag).get();
	}

	/**
	 * @author chaoyang.li
	 * @param tag
	 */
	public static final synchronized Session openSession(String tag) {
		Session session = sessions.get(tag).get();
		if (session != null && session.isOpen()) {
			return session;
		}
		sessions.get(tag).set(hibernateSessionFactoryProvider.buildSessionFactory(tag).openSession());
		return sessions.get(tag).get();
	}

	/**
	 * @author chaoyang.li
	 * @param tag
	 */
	public static final synchronized Statistics getStatistics(String tag) {
		return hibernateSessionFactoryProvider.buildSessionFactory(tag).getStatistics();
	}

	/**
	 * @author chaoyang.li
	 * @param tag
	 */
	public static final synchronized void close(String tag) {
		try {
			if (sessions.get(tag).get() != null) {
				sessions.get(tag).get().close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
